//
//  YROAuthViewController.swift
//  YR 微博
//
//  Created by cyr on 15/10/11.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit
import SVProgressHUD

class YROAuthViewController: UIViewController,UIWebViewDelegate {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
        
        title = "新浪微博"
        
        // 设置导航栏的title 和关闭按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    /**
    关闭界面
    */
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        view.backgroundColor = UIColor.whiteColor()
        webView.loadRequest(NSURLRequest(URL: YRNetworkTools.sharedTools.oauthUrl()))
        
    }
    
    // MARK: -UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
//        print("开始")
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
//        print("结束")
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
        // 判断是否包含回调地址
        if !urlString.hasPrefix(YRNetworkTools.sharedTools.redirectUri) {
            return true
        }
//
        if let query = request.URL?.query where query.hasPrefix("code=") {
            print("获取授权码")
            
//            let code  = query.substringFromIndex(advance(query.startIndex,"code=".characters.count))
            
            let code = query.substringFromIndex("code=".endIndex)
            
            print(code)
            
            // 换取 Token
            loadAccessToken(code)
            
            
        } else {
            close()
        }
        
        return false
    }
    
    private func loadAccessToken(code:String) {
      
        YRNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in

            if result == nil || error != nil  {
            // 延迟一段时间后就关闭
             
                self.netError()
                return
            }

            
            YRUserAccount(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil {
                self.netError()
                return
                }
                // 发送通知切换视图控制器
                NSNotificationCenter.defaultCenter().postNotificationName(YRRootViewControllerSwitchNotification, object: false)
                
                // 关闭控制器
                self.close()
            })
        }
    }
    
    private func netError() {
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
        
        // 延迟一段时间后就关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            self.close()
        })

    }
}


 